<template>
  <view class="repair-page">
    <!-- 核销码和二维码 -->
    <view class="repair-section repair-qrcode" v-if="repairRecord">
      <view class="repair-qrcode-row">
        <text class="repair-qrcode-label">核销码：</text>
        <text class="repair-qrcode-value">{{ repairRecord.verificationCode || 'N/A' }}</text>
      </view>
      <!-- 假设后端返回二维码图片URL，否则使用静态或生成 -->
      <image class="repair-qrcode-img" :src="repairRecord.qrCodeUrl || '/static/二维码@3x.png'" mode="aspectFit"></image>
    </view>
    <!-- 维修信息 -->
    <view class="repair-section" v-if="repairRecord">
      <view class="repair-title">维修信息</view>
      <view class="repair-divider"></view>
      <view class="repair-info-row"><text class="repair-info-label">维修单号：</text><text class="repair-info-value">{{ repairRecord.id || 'N/A' }}</text></view>
      <view class="repair-info-row"><text class="repair-info-label">维修状态：</text><text class="repair-info-value">{{ formatRepairStatus(repairRecord.status) }}</text></view>
      <view class="repair-info-row"><text class="repair-info-label">车主姓名：</text><text class="repair-info-value">{{ repairRecord.name || 'N/A' }}</text></view>
      <view class="repair-info-row"><text class="repair-info-label">联系方式：</text><text class="repair-info-value">{{ repairRecord.phone || 'N/A' }}</text></view>
      <view class="repair-info-row"><text class="repair-info-label">维修方式：</text><text class="repair-info-value">{{ repairRecord.type || 'N/A' }}</text></view>
      <view class="repair-info-row"><text class="repair-info-label">取车位置：</text><text class="repair-info-value">{{ repairRecord.location || 'N/A' }}</text></view>
      <view class="repair-info-row"><text class="repair-info-label">预约日期：</text><text class="repair-info-value">{{ formatDate(repairRecord.reservationTime) }}</text></view>
      <!-- 提交日期数据库截图未见对应字段，暂时保留或移除 -->
      <view class="repair-info-row"><text class="repair-info-label">提交日期：</text><text class="repair-info-value">{{ formatDate(repairRecord.createTime) }}</text></view>
    </view>
    <!-- 车辆信息 -->
    <view class="repair-section" v-if="repairRecord">
      <view class="repair-title">车辆信息</view>
      <view class="repair-divider"></view>
      <view class="repair-info-row"><text class="repair-info-label">车辆类型：</text><text class="repair-info-value">{{ carTypeName }}</text></view>
      <view class="repair-info-row"><text class="repair-info-label">车牌号：</text><text class="repair-info-value">{{ repairRecord.carNum || 'N/A' }}</text></view>
      <view class="repair-info-row">
        <text class="repair-info-label">整车照片：</text>
        <image v-if="repairRecord.vehiclePhotos" class="repair-car-img" :src="repairRecord.vehiclePhotos.split(',')[0]" mode="aspectFill"></image>
        <text v-else class="repair-info-value">无</text>
      </view>
      <view class="repair-info-row">
        <text class="repair-info-label">维修部位照片：</text>
        <view class="repair-car-img-list" v-if="repairRecord.repairPhotos && repairRecord.repairPhotos.split(',').length > 0">
          <image v-for="(img, index) in repairRecord.repairPhotos.split(',')" :key="index" class="repair-car-img" :src="img" mode="aspectFill"></image>
        </view>
        <text v-else class="repair-info-value" style="margin-left: 8rpx;">无</text>
      </view>
    </view>
    <!-- 底部按钮 -->
    <!-- 按钮的显示逻辑需要根据后端返回的状态（status）来判断 -->
    <view class="repair-bottom-btn-bar" v-if="repairRecord">
      <!-- 假设 status 为 0 是进行中 -->
      <!-- <button class="repair-bottom-btn" style="float:left;margin-right:10px;background:#52c41a;" @click="onFinish" v-if="repairRecord.status === 0">已完成</button> -->
      <!-- 假设 status 为 0 是进行中，可以取消 -->
      <button class="repair-bottom-btn" @click="showCancelModal = true" v-if="repairRecord.status === 0">取消订单</button>
    </view>

    <!-- 取消订单模态框 -->
    <view v-if="showCancelModal" class="cancel-modal-mask">
      <view class="cancel-modal-panel">
        <view class="cancel-modal-title">确认取消预约么？</view>
        <view class="cancel-modal-btns">
          <button class="cancel-modal-btn" @click="showCancelModal = false">取消</button>
          <button class="cancel-modal-btn confirm" @click="onCancelConfirm">确认</button>
        </view>
      </view>
    </view>

    <!-- 加载和无数据状态 -->
     <view v-if="loading" class="loading-text">加载中...</view>
     <view v-if="!repairRecord && !loading" class="empty-text">暂无相关维修记录</view>

  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import baseUrl from '@/untils/urlConfig';

 // 引入 baseUrl
// ** 临时模拟本地存储的用户信息和 Token，用于测试 **
// ** 在实际应用中，请移除此段代码，改为用户登录成功后存储真实信息 **
// uni.setStorageSync('userInfo', { userId: 1 }); // 假设用户ID为1
// uni.setStorageSync('token', 'YOUR_ACTUAL_TOKEN'); // 替换为你的实际有效 token
// ** 临时模拟本地存储结束 **

// 获取当前登录用户ID和token
const getCurrentUser = () => {
  const userInfo = uni.getStorageSync('userInfo');
  const token = uni.getStorageSync('token');
  // 暂时不强制检查登录状态，方便调试
  // if (!userInfo || !userInfo.userId || !token) {
  //   uni.showToast({
  //     title: '请先登录或检查本地存储',
  //     icon: 'none'
  //   });
    // 跳转到登录页面
    // setTimeout(() => {
    //   uni.navigateTo({
    //     url: '/pages/login/login'
    //   });
    // }, 1500);
  //   return null;
  return { userId: userInfo ? userInfo.userId : null, token: token };
};


// 响应式数据
const showCancelModal = ref(false);
// const repairStatus = ref('进行中'); // 移除静态状态
// const showCancelBtn = ref(true); // 移除静态按钮显示控制
const repairRecord = ref(null); // 用于存储从后端获取的维修记录
const loading = ref(true); // 加载状态
const carTypeName = ref('N/A'); // 新增：用于存储车型名称

// 格式化日期函数
const formatDate = (dateString) => {
  if (!dateString) return 'N/A';
  const date = new Date(dateString);
  if (isNaN(date.getTime())) return dateString; // 如果日期无效，返回原字符串
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  return `${year}/${month}/${day} ${hours}:${minutes}`;
};

// 格式化维修状态
const formatRepairStatus = (status) => {
  // 假设后端 status 字段的映射关系
  const statusMap = {
    0: '进行中',
    1: '已完成',
    // 根据后端实际状态码添加其他状态
    // 2: '已取消',
    // 3: '待处理',
  };
  return statusMap[status] || '未知状态';
};

// 获取车型名称的方法
const fetchCarTypeName = async (carTypeId) => {
  const user = getCurrentUser();
  try {
    const response = await uni.request({
      url: baseUrl + '/chy/car_type/list', // 假设车型接口支持通过id查询
      method: 'GET',
      data: {
        id: carTypeId
      },
       header: {
        // 使用您提供的硬编码 token 或本地存储的 token
        ...(user && user.token ? { 'Authorization': `Bearer eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6ImExY2Y2YzQ1LWQ3NGYtNDNhZC04Nzc2LTc5ZjVjZTYzYzJhNCIsInVzZXJuYW1lIjoiYWRtaW4ifQ.sVcpT_LwYzWmTz2keOUxQnysqcNWp6nQ7gf3vdidU5Kc4kejJck3gtAjySJDDsGQfRbTP6O-1zMGX8MnxrWfdw` } : {})
      }
    });

    console.log('Car type response:', response); // 添加日志

    if (response.statusCode === 200 && response.data && response.data.code === 200) {
      const carTypes = response.data.rows || [];
      if (carTypes.length > 0) {
        // 查找与传入 carTypeId 匹配的车型
        const matchedCarType = carTypes.find(type => type.id === carTypeId); // 假设车型ID字段是 id
        if (matchedCarType) {
           carTypeName.value = matchedCarType.name; // 假设车型名称字段是 name
           console.log('Fetched car type name:', carTypeName.value); // 添加日志
        } else {
          carTypeName.value = '未知车型';
           console.log('Car type not found in list for id:', carTypeId); // 添加日志
        }
      } else {
        carTypeName.value = '未知车型';
         console.log('Car type list is empty for id:', carTypeId); // 添加日志
      }
    } else {
      console.error('获取车型信息失败:', response); // 添加日志
      carTypeName.value = '获取失败';
    }
  } catch (error) {
    console.error('请求车型信息失败:', error); // 添加日志
    carTypeName.value = '加载失败';
  }
};

// 获取维修记录数据的方法
const fetchRepairData = async () => {
  loading.value = true;
  const user = getCurrentUser();
  // 暂时不强制用户登录
  // if (!user || !user.userId) {
  //    loading.value = false;
  //   return;
  // }

  try {
    // 1. 调用维修记录接口
    const response = await uni.request({
      url: baseUrl + '/chy/reservation/list', // 将 /repair/list 修改为 /reservation/list
      method: 'GET',
      data: {
        uid: user ? user.userId : null // 传递用户ID，如果用户未登录则传递 null 或其他后端期望的值
        // 根据后端 Record 参数定义，可能需要传递其他筛选条件
        // 例如：status: 0 // 只获取进行中的维修记录
      },
      header: {
        // 只有在获取到 token 时才添加 Authorization 头部
        ...(user && user.token ? { 'Authorization': `eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6ImExY2Y2YzQ1LWQ3NGYtNDNhZC04Nzc2LTc5ZjVjZTYzYzJhNCIsInVzZXJuYW1lIjoiYWRtaW4ifQ.sVcpT_LwYzWmTz2keOUxQnysqcNWp6nQ7gf3vdidU5Kc4kejJck3gtAjySJDDsGQfRbTP6O-1zMGX8MnxrWfdw` } : {})
      }
    });

    console.log('Repair list response:', response); // 添加日志

    if (response.statusCode === 200 && response.data && response.data.code === 200) {
      const records = response.data.rows || [];
      if (records.length > 0) {
        // 假设我们只展示用户最新的或第一条维修记录
        // 如果需要展示特定记录，需要从页面参数获取ID并传递给后端
        repairRecord.value = records[0]; // 取列表中的第一条记录
         console.log('Fetched repair record:', repairRecord.value); // 添加日志

         // 获取车辆类型名称
         if (repairRecord.value && repairRecord.value.carTypeId) {
           await fetchCarTypeName(repairRecord.value.carTypeId);
         }

      } else {
        repairRecord.value = null; // 没有找到记录
         console.log('No repair records found for user.'); // 添加日志
      }
    } else {
      const errorMessage = response.data && response.data.msg ? response.data.msg : '获取维修记录失败';
      uni.showToast({ title: errorMessage, icon: 'none' });
      console.error('获取维修记录失败:', response); // 添加日志
      repairRecord.value = null; // 清空数据
    }

  } catch (error) {
    console.error('请求失败:', error); // 添加日志
    uni.showToast({ title: '网络请求失败', icon: 'none' });
    repairRecord.value = null; // 清空数据
  } finally {
    loading.value = false;
  }
};

// 页面加载时获取数据
onMounted(() => {
  console.log('Repair page onMounted: calling fetchRepairData'); // 添加日志
  fetchRepairData();
});

// 取消订单确认
const onCancelConfirm = () => {
  // TODO: 调用后端取消订单接口，需要根据 repairRecord.value.id 发送请求
  console.log('Cancelling repair record with ID:', repairRecord.value.id);
  // 假设取消接口是 DELETE /chy/repair/{id}
  // uni.request({
  //    url: baseUrl + '/chy/repair/' + repairRecord.value.id,
  //    method: 'DELETE',
      // header: { ...(user && user.token ? { 'Authorization': `Bearer ${user.token}` } : {}) },
  //    success: (res) => {
  //      if (res.statusCode === 200 && res.data.code === 200) {
  //         uni.showToast({ title: '取消成功', icon: 'success' });
  //         showCancelModal.value = false;
  //         fetchRepairData(); // 刷新数据
  //      } else {
  //         uni.showToast({ title: res.data.msg || '取消失败', icon: 'none' });
  //      }
  //    },
  //    fail: () => {
  //       uni.showToast({ title: '取消请求失败', icon: 'none' });
  //    }
  // });
   showCancelModal.value = false; // 暂时关闭模态框
  uni.redirectTo({ url: '/pages/repair/repair-cancel' }); // 根据实际流程确定跳转
};

// 完成维修
const onFinish = () => {
   // TODO: 调用后端标记完成接口，需要根据 repairRecord.value.id 发送请求
  console.log('Finishing repair record with ID:', repairRecord.value.id);
  // 假设完成接口是 PUT /chy/repair/finish/{id} 或类似的
  // uni.request({
  //    url: baseUrl + '/chy/repair/finish/' + repairRecord.value.id,
  //    method: 'PUT', // 或 POST
      // header: { ...(user && user.token ? { 'Authorization': `Bearer ${user.token}` } : {}) },
  //    success: (res) => {
  //      if (res.statusCode === 200 && res.data.code === 200) {
  //         uni.showToast({ title: '标记完成成功', icon: 'success' });
  //         fetchRepairData(); // 刷新数据
  //      } else {
  //         uni.showToast({ title: res.data.msg || '标记完成失败', icon: 'none' });
  //      }
  //    },
  //    fail: () => {
  //       uni.showToast({ title: '标记完成请求失败', icon: 'none' });
  //    }
  // });
  // repairStatus.value = '已完成'; // 移除静态更新
  // showCancelBtn.value = false; // 移除静态更新
};


</script>
<style>
.repair-page {
  background: #fafafa;
  min-height: 100vh;
  padding-bottom: 120rpx;
}
.repair-section {
  background: #fff;
  border-radius: 32rpx;
  margin: 32rpx 24rpx 0 24rpx;
  padding: 32rpx 32rpx 18rpx 32rpx;
  box-shadow: 0 8rpx 32rpx rgba(35,138,255,0.04);
}
.repair-qrcode {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-bottom: 36rpx;
}
.repair-qrcode-row {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 18rpx;
}
.repair-qrcode-label {
  font-size: 32rpx;
  color: #222;
  font-weight: 500;
}
.repair-qrcode-value {
  font-size: 32rpx;
  color: #444;
  margin-left: 16rpx;
  font-weight: 500;
}
.repair-qrcode-img {
  width: 200rpx;
  height: 200rpx;
  margin-top: 8rpx;
}
.repair-title {
  font-size: 32rpx;
  color: #222;
  font-weight: bold;
  margin-bottom: 12rpx;
}
.repair-divider {
  height: 2rpx;
  background: #f2f2f2;
  margin-bottom: 18rpx;
  border-radius: 2rpx;
}
.repair-info-row {
  display: flex;
  align-items: center;
  margin-bottom: 14rpx;
}
.repair-info-label {
  color: #222;
  font-size: 28rpx;
  min-width: 180rpx;
  font-weight: 500;
}
.repair-info-value {
  color: #b0b0b0;
  font-size: 28rpx;
  margin-left: 8rpx;
}
.repair-car-img {
  width: 120rpx;
  height: 120rpx;
  border-radius: 16rpx;
  margin-left: 8rpx;
  margin-top: 8rpx;
  background: #f7f7f7;
}
.repair-car-img-list {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-left: 8rpx;
}
.repair-bottom-btn-bar {
  margin-top:30rpx;
  bottom: 32rpx;
  display: flex;
  justify-content: center;
  float: right;
  margin-right: 18px;
  z-index: 10;
}
.repair-bottom-btn {
  background: #238aff;
  color: #fff;
  font-size: 25rpx;
  font-weight: 500;
  border-radius: 32rpx;
  padding: 5rpx 50rpx;
  border: none;
  border-radius: 50px;
  box-shadow: 0 2rpx 8rpx rgba(35,138,255,0.10);
}
.cancel-modal-mask {
  position: fixed;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.18);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}
.cancel-modal-panel {
  background: #fff;
  border-radius: 24rpx;
  min-width: 500rpx;
  padding: 48rpx 0 36rpx 0;
  box-shadow: 0 2rpx 16rpx rgba(0,0,0,0.08);
  display: flex;
  flex-direction: column;
  align-items: center;
}
.cancel-modal-title {
  font-size: 30rpx;
  color: #222;
  text-align: center;
  margin-bottom: 38rpx;
}
.cancel-modal-btns {
  display: flex;
  flex-direction: row;
  justify-content: center;
  width: 100%;
}
.cancel-modal-btn {
  background: #f2f2f2;
  color: #444;
  border: none;
  border-radius: 50px;
  font-size: 25rpx;
  padding: 5rpx 40rpx;
  margin: 0 24rpx;
}
.cancel-modal-btn.confirm {
  background: #238aff;
  color: #fff;
}
.loading-text {
  text-align: center;
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #444;
}
.empty-text {
  text-align: center;
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #444;
}
</style> 